#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>

int create_tcp_server_socket(char *ip, int port)
{
    signal(SIGPIPE, SIG_IGN);

    int sockfd;
    int sockaddr_len;

    struct in_addr server_ip;
    struct sockaddr_in server_addr;
    // 1、socket函数创建套接字 -->  文件描述符
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket create failed!\n");
        exit(1);
    }
    printf("socket create Success! %d\n", sockfd);

    int reuse = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    //??为什么要绑定IP和端口号？接受客户端的连接，就需要确定服务器的IP和端口号
    // 2、bind：给套接字绑定IP地址和端口号
    // 初始化struct sockadd_in变量；

    inet_pton(AF_INET, ip, (void *)&server_ip);
    server_addr.sin_family = AF_INET;   // IPV4
    server_addr.sin_addr = server_ip;   // IP
    server_addr.sin_port = htons(port); // h:host to n:net

    if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0)
    {
        perror("bind ip & port failed!");
        exit(1);
    }
    printf("bind Success ip = %s port = %d\n", ip, port);

    // 3、listen：监听：允许其他人进行连接请求
    if (listen(sockfd, 20) < 0)
    {
        perror("listen failed!\n");
        exit(1);
    }
    printf("listen Success!\n");

    return sockfd;
}

void setnonblock(int sockfd)
{
    int flags = fcntl(sockfd, F_GETFL);
    flags = flags | O_NONBLOCK;
    fcntl(sockfd, F_SETFL, flags);
}

int main(int argc, char **argv)
{
    if (argc != 3)
    {
        printf("Please input server bind ip and port!\n");
        exit(1);
    }
    pid_t pid;
    int sockfd;
    int r_len;
    int confd;
    int tempfd;
    int sockaddr_len;
    char message[1024] = {0};
    char client_ip[INET_ADDRSTRLEN];
    struct sockaddr_in client_addr;

    int client_fds[1024];
    for (int i = 0; i < 1024; i++)
    {
        client_fds[i] = -1;
    }

    sockfd = create_tcp_server_socket(argv[1], atoi(argv[2]));

    // 4、accept: 处理连接请求：三次握手
    while (1)
    {
        sockaddr_len = sizeof(struct sockaddr);
        // confd:连接描述符（文件描述符） 每成功连接一个客户端，对应生成唯一的连接描述符
        confd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t *)&sockaddr_len);
        if (confd < 0)
        {
            perror("accept failed!");
            exit(1);
        }

        inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip));
        printf("client ip = %s port = %d\n", client_ip, client_addr.sin_port);
        printf("confd = %d\n", confd);

        if ((pid = fork()) < 0)
        {
            perror("fork error!");
            exit(1);
        }

        if (pid == 0)
        {
            // client IO
            while (1)
            {
                r_len = read(confd, message, sizeof(message));
                if (r_len < 0)
                {
                    perror("read client message error!");
                    exit(1);
                }
                else if (r_len == 0)
                {
                    printf("client is close!\n");
                    shutdown(confd, SHUT_RDWR);
                    exit(1);
                }
                else if (r_len > 0)
                {
                    message[r_len] = '\0';
                    printf("recv client msg: %s\n", message);
                    // send(tempfd, "OK\n", 3, 0); // 如果confd已经断开（关闭),如果继续发送，产生一个SIGPIPE，终止当前进程
                    write(confd, "OK\n", 3);
                }
            }
        }
        else if (pid > 0)
        {
            close(confd);
        } 
    }

    // 6、close/shutdown： 关闭连接

    return 0;
}